import 'package:auto_orientation/auto_orientation.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class PlayVideo extends StatefulWidget {
  PlayVideo({Key key, this.title,this.url,this.timer=5000,this.id}) : super(key: key);
  final String title;
  final String url;
  final int timer;
  final String id;

  @override
  _PlayVideoState createState() => _PlayVideoState();
}

class _PlayVideoState extends State<PlayVideo> {
  VideoPlayerController _controller;
  bool startedPlaying = false;
  bool get _isFullScreen => MediaQuery.of(context).orientation == Orientation.landscape;
  int totalTime = 0;
  TimerUtil _timerUtil;
  @override
  void initState() {
    setState(() {
      totalTime = widget.timer;
    });
    super.initState();
    _controller = VideoPlayerController.network(widget.url);
    _controller.addListener(() {
      setState(() {});
    });
    _controller.setLooping(true);
    _controller.setVolume(1);
    _timerUtil = TimerUtil(mTotalTime: totalTime);
    _controller.initialize().then((_) => setState(() {
    }));
    _timerUtil.setOnTimerTickCallback((int tick) {
      setState(() {
        totalTime -= 1000;
      });
    });
    _controller.play();
    _timerUtil.startCountDown();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
          child: InkWell(
            onTap: (){
              if(totalTime>0){
                totalTime = 0;
              }else{
                totalTime = widget.timer;
                _timerUtil.updateTotalTime(totalTime);
              }
            },
            child: Container(
              color: Colors.black,
              child: _controller.value.initialized
                  ? AspectRatio(
                aspectRatio: !_isFullScreen?16 / 9
                    :MediaQuery.of(context).size.width / MediaQuery.of(context).size.height,
                child: Center(
                  child: Stack(
                    alignment: Alignment.bottomCenter,
                    children: <Widget>[
                      VideoPlayer(_controller),
                      _PlayPauseOverlay(controller: _controller),
                      totalTime>0?_BottomStyle(
                        controller: _controller,
                        isFullScreen: _isFullScreen,
                      ):SizedBox.shrink(),
                      totalTime>0?Positioned(
                          left: MediaQuery.of(context).padding.left,
                          top: MediaQuery.of(context).padding.top,
                          right: MediaQuery.of(context).padding.right,
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              IconButton(
                                icon: Icon(Icons.arrow_back,color: Colors.white),
                                onPressed: (){
                                  !_isFullScreen?Navigator.pop(context):AutoOrientation.portraitAutoMode();
                                },
                              ),
                              !_isFullScreen?SizedBox.shrink():Expanded(
                                child: Text(widget.title,
                                  maxLines:1,
                                  textAlign: TextAlign.start,
                                  style: TextStyle(
                                      fontSize: 16,color: Colors.white,wordSpacing: 2,fontWeight: FontWeight.bold
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              IconButton(
                                icon: Icon(Icons.star_half,color: Colors.white),
                                onPressed: (){
                                  print('分享');
                                },
                              ),
                            ],
                          )
                      ):SizedBox.shrink()
                    ],
                  ),
                ),
              ):AspectRatio(
                aspectRatio: !_isFullScreen?16 / 9
                    :MediaQuery.of(context).size.width / MediaQuery.of(context).size.height,
                child: Stack(
                  children: <Widget>[
                    Center(
                      child: CircularProgressIndicator(
                        strokeWidth: 4.0,
                      ),
                    ),
                    Positioned(
                      left: MediaQuery.of(context).padding.left,
                      top: MediaQuery.of(context).padding.top,
                      child: IconButton(
                        icon: Icon(Icons.arrow_back,color: Colors.white),
                        onPressed: (){
                          !_isFullScreen?Navigator.pop(context):AutoOrientation.portraitAutoMode();
                        },
                      ),
                    )
                  ],
                )
              )
            ),
          )
    );
  }
  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _timerUtil.cancel();
  }
}

class _BottomStyle extends StatefulWidget {
  final VideoPlayerController controller;
  final bool isFullScreen;
  _BottomStyle({Key key, this.controller, this.isFullScreen}) : super(key: key);
  @override
  __BottomStyleState createState() => __BottomStyleState();
}
class __BottomStyleState extends State<_BottomStyle> {
  VideoPlayerController get controller => widget.controller;
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Colors.black12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          IconButton(
              icon: Icon(
                controller.value.isPlaying
                    ? Icons.pause_circle_outline
                    : Icons.play_circle_outline,
                color: Colors.white,
              ),
              onPressed: () {
                if (controller.value.isPlaying) {
                  setState(() {
                    controller.pause();
                  });
                } else {
                  controller.play();
                }
              }),
          Container(
            alignment: Alignment.center,
            height: 20,
            child: Row(
              children: <Widget>[
                Container(
                  alignment: Alignment.centerRight,
                  width: 50,
                  child: Text(
                      '${DateUtil.formatDateMs(controller.value.position.inMilliseconds, isUtc: true, format: DataFormats.h_m_s)}',
                      style: TextStyle(color: Colors.white, fontSize: 10)),
                ),
                SizedBox(width: 1,),
                Text('/',style: TextStyle(color: Colors.white, fontSize: 10)),
                SizedBox(width: 1,),
                Text(
                    '${DateUtil.formatDateMs(controller.value.duration.inMilliseconds, isUtc: true, format: DataFormats.h_m_s)}',
                    style: TextStyle(color: Colors.white, fontSize: 10)),

              ],
            )
          ),
          VideoProgressIndicator(controller,
              allowScrubbing: true,
              colors: VideoProgressColors(
                  playedColor: Theme.of(context).primaryColor,
                  bufferedColor: Colors.black26,
                  backgroundColor: Colors.white)),
          IconButton(
              icon: Icon(
                controller.value.volume<1?Icons.volume_off:Icons.volume_up,
                color: Colors.white,
              ),
              onPressed: () {
                if(controller.value.volume<1){
                  controller.setVolume(1);
                }else{
                  controller.setVolume(0);
                }
              }),
          IconButton(
              icon: Icon(
                !widget.isFullScreen?Icons.fullscreen:Icons.fullscreen_exit,
                color: !widget.isFullScreen?Colors.white:Theme.of(context).primaryColor,
              ),
              onPressed: () {
                setState(() {
                  if (widget.isFullScreen) {
                    AutoOrientation.portraitAutoMode();
                  } else {
                    AutoOrientation.landscapeAutoMode();
                  }
                });
              }),
        ],
      ),
    );
  }
}

class _PlayPauseOverlay extends StatelessWidget {
  const _PlayPauseOverlay({Key key, this.controller}) : super(key: key);
  final VideoPlayerController controller;
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        controller.value.isPlaying?SizedBox.shrink():AnimatedSwitcher(
          duration: Duration(milliseconds: 50),
          reverseDuration: Duration(milliseconds: 200),
          child: Container(
            color: Colors.black26,
            child: Center(
              child: IconButton(
                icon: Icon(Icons.play_circle_outline,
                  color: Theme.of(context).primaryColor,
                  size: 50.0),
                onPressed: (){
                  controller.play();
                },
              ),
            ),
          )
        ),
      ],
    );
  }
}

class VideoProgressIndicator extends StatefulWidget {
  VideoProgressIndicator(
    this.controller, {
    VideoProgressColors colors,
    this.allowScrubbing,
  }) : colors = colors ?? VideoProgressColors();
  final VideoPlayerController controller;
  final VideoProgressColors colors;
  final bool allowScrubbing;
  @override
  _VideoProgressIndicatorState createState() => _VideoProgressIndicatorState();
}

class _VideoProgressIndicatorState extends State<VideoProgressIndicator> {
  _VideoProgressIndicatorState() {
    listener = () {
      if (!mounted) {
        return;
      }
      setState(() {});
    };
  }
  VoidCallback listener;
  VideoPlayerController get controller => widget.controller;
  VideoProgressColors get colors => widget.colors;
  @override
  void initState() {
    super.initState();
    controller.addListener(listener);
  }
  @override
  void deactivate() {
    controller.removeListener(listener);
    super.deactivate();
  }
  @override
  Widget build(BuildContext context) {
    Widget progressIndicator;
    if (controller.value.initialized) {
      final int duration = controller.value.duration.inMilliseconds;
      final int position = controller.value.position.inMilliseconds;
      int maxBuffering = 0;
      for (DurationRange range in controller.value.buffered) {
        final int end = range.end.inMilliseconds;
        if (end > maxBuffering) {
          maxBuffering = end;
        }
      }
      progressIndicator = Stack(
        fit: StackFit.passthrough,
        children: <Widget>[
          LinearProgressIndicator(
            value: maxBuffering / duration,
            valueColor: AlwaysStoppedAnimation<Color>(colors.bufferedColor),
            backgroundColor: colors.backgroundColor,
          ),
          LinearProgressIndicator(
            value: position / duration,
            valueColor: AlwaysStoppedAnimation<Color>(colors.playedColor),
            backgroundColor: Colors.transparent,
          ),
        ],
      );
    } else {
      progressIndicator = LinearProgressIndicator(
        value: null,
        valueColor: AlwaysStoppedAnimation<Color>(colors.playedColor),
        backgroundColor: colors.backgroundColor,
      );
    }
    final Widget paddedProgressIndicator = Container(
      height: 5,
      width: MediaQuery.of(context).size.width * (1 / 2)-80,
      child: progressIndicator,
    );
    if (widget.allowScrubbing) {
      return _VideoScrubber(
        child: paddedProgressIndicator,
        controller: controller,
      );
    } else {
      return paddedProgressIndicator;
    }
  }
}

class _VideoScrubber extends StatefulWidget {
  _VideoScrubber({
    @required this.child,
    @required this.controller,
  });
  final Widget child;
  final VideoPlayerController controller;
  @override
  _VideoScrubberState createState() => _VideoScrubberState();
}

class _VideoScrubberState extends State<_VideoScrubber> {
  bool _controllerWasPlaying = false;
  VideoPlayerController get controller => widget.controller;
  @override
  Widget build(BuildContext context) {
    void seekToRelativePosition(Offset globalPosition) {
      final RenderBox box = context.findRenderObject();
      final Offset tapPos = box.globalToLocal(globalPosition);
      final double relative = tapPos.dx / box.size.width;
      final Duration position = controller.value.duration * relative;
      controller.seekTo(position);
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: widget.child,
      onHorizontalDragStart: (DragStartDetails details) {
        if (!controller.value.initialized) {
          return;
        }
        _controllerWasPlaying = controller.value.isPlaying;
        if (_controllerWasPlaying) {
          controller.pause();
        }
      },
      onHorizontalDragUpdate: (DragUpdateDetails details) {
        if (!controller.value.initialized) {
          return;
        }
        seekToRelativePosition(details.globalPosition);
      },
      onHorizontalDragEnd: (DragEndDetails details) {
        if (_controllerWasPlaying) {
          controller.play();
        }
      },
      onTapDown: (TapDownDetails details) {
        if (!controller.value.initialized) {
          return;
        }
        seekToRelativePosition(details.globalPosition);
      },
    );
  }
}
